using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MESData.ErrorCode;
using MESData.ProductionPlan.API.DTO;
using MESData.ProductionPlan.API.Services;
using MESData.ProductionPlan.API.Extensions;
using System.IO;

namespace MESData.ProductionPlan.API.Controllers
{
    /// <summary>
    /// 生产计划控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize] // 添加认证要求
    public class ProductionPlanController : ControllerBase
    {
        private readonly IProductionPlanService _productionPlanService;

        public ProductionPlanController(IProductionPlanService productionPlanService)
        {
            _productionPlanService = productionPlanService;
        }

        /// <summary>
        /// 新增生产计划
        /// </summary>
        [HttpPost("create")]
        public async Task<ApiResult<bool>> CreateProductionPlan([FromBody] ProductionPlanDto dto)
        {
            var operatorName = User.GetUserAccount();
            return await _productionPlanService.CreateProductionPlanAsync(dto, operatorName);
        }

        /// <summary>
        /// 分页查询生产计划
        /// </summary>
        [HttpPost("page")]
        [AllowAnonymous] // 查询接口允许匿名访问
        public async Task<ApiResult<ProductionPlanPageResultDto>> GetProductionPlansPage([FromBody] ProductionPlanQueryDto queryDto)
        {
            return await _productionPlanService.GetProductionPlansPageAsync(queryDto);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        [HttpPost("upload")]
        public async Task<ApiResult<string>> UploadFile(IFormFile file, int productionPlanId)
        {
            var operatorName = User.GetUserAccount();
            return await _productionPlanService.UploadFileAsync(file, productionPlanId, operatorName);
        }

        /// <summary>
        /// 逻辑删除生产计划
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<ApiResult<bool>> SoftDelete(int id)
        {
            var operatorName = User.GetUserAccount();
            return await _productionPlanService.SoftDeleteAsync(id, operatorName);
        }

        /// <summary>
        /// 生产计划详情
        /// </summary>
        [HttpGet("{id}")]
        [AllowAnonymous] // 详情接口允许匿名访问
        public async Task<ApiResult<ProductionPlanDetailDto>> Detail(int id)
        {
            return await _productionPlanService.GetDetailAsync(id);
        }

        /// <summary>
        /// 导出生产计划（Excel）- 返回文件下载
        /// </summary>
        [HttpGet("{id}/export")] 
        public async Task<IActionResult> ExportPlan(int id)
        {
            var result = await _productionPlanService.ExportPlanAsync(id);
            if (result.Code != ApiEnum.Success)
            {
                return BadRequest(result);
            }

            var fileName = $"生产计划_{id}_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            
            return File(result.Data, contentType, fileName);
        }

        /// <summary>
        /// 导出生产物品（Excel）- 返回文件下载
        /// </summary>
        [HttpGet("{id}/export-items")] 
        public async Task<IActionResult> ExportItems(int id)
        {
            var result = await _productionPlanService.ExportProductedItemsAsync(id);
            if (result.Code != ApiEnum.Success)
            {
                return BadRequest(result);
            }

            var fileName = $"生产物品_{id}_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            
            return File(result.Data, contentType, fileName);
        }

        /// <summary>
        /// 导出操作记录（Excel）- 返回文件下载
        /// </summary>
        [HttpGet("{id}/export-logs")] 
        public async Task<IActionResult> ExportLogs(int id)
        {
            var result = await _productionPlanService.ExportOperationLogsAsync(id);
            if (result.Code != ApiEnum.Success)
            {
                return BadRequest(result);
            }

            var fileName = $"操作记录_{id}_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            
            return File(result.Data, contentType, fileName);
        }

        /// <summary>
        /// 导出生产计划列表（支持查询条件）
        /// </summary>
        [HttpPost("export")]
        public async Task<IActionResult> ExportProductionPlans([FromBody] ProductionPlanQueryDto queryDto)
        {
            var result = await _productionPlanService.ExportProductionPlansAsync(queryDto);
            if (result.Code != ApiEnum.Success)
            {
                return BadRequest(result);
            }

            var fileName = $"生产计划列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            
            return File(result.Data, contentType, fileName);
        }
    }
} 